package javamobile.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.util.Map;

import javamobile.controller.Controller;

public class ServerSocketThread implements Runnable{
	private Socket client = null;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private Controller controller = new Controller();
	
	public ServerSocketThread(Socket client) {
		super();
		this.client = client;
	}



	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		System.out.println("Recieved one socket request on " + client.getInetAddress().getHostAddress());
		try {
			out = new ObjectOutputStream(client.getOutputStream());
			in = new ObjectInputStream(client.getInputStream());

    		
    		
    		Map<String, Object> input = (Map<String, Object>) in.readObject();
			String action = (String) input.get("action");
    		Map<String, Object> output = controller.performAction(action, input);
    		out.writeObject(output);
			
		} catch (IOException e) {
	        System.err.println("Could not listen on port."); 
			e.printStackTrace();
	        System.exit(-1); 
		} catch (ClassNotFoundException e) {
	        System.err.println("ClassNotFoundException"); 
			e.printStackTrace();
	        System.exit(-1); 
		}
		finally {
			try {
				out.close();
				in.close();
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
	
}
